package com.dingyx.ps.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.dingyx.ps.mapper.MemberListMapper;
import com.dingyx.ps.model.ReturnT;
import com.dingyx.ps.model.entity.MemberListDTO;
import com.dingyx.ps.model.po.WXInfoPO;
import com.dingyx.ps.model.po.WXLoginPO;
import com.dingyx.ps.redis.RedisTemplateDao;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 微信小程序用户接口
 * @author dingyuxin
 */
@RestController
@Api(description="小程序基础接口")
@AllArgsConstructor
@Slf4j
@RequestMapping("/wx/user")
public class WxMaUserController extends RedisTemplateDao {
    private final WxMaService wxMaService;
    @Resource
    private MemberListMapper memberListMapper;
    /**
     * 登陆接口
     */
    @ApiOperation(value = "小程序登陆")
    @PostMapping("/login")
    public ReturnT login(@RequestBody @Validated WXLoginPO param) {
        if (!wxMaService.switchover(param.getAppId())) {
            return ReturnT.ERROR("未找到对应appId的配置，请核实！");
        }

        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(param.getCode());
            log.info(session.getSessionKey());
            log.info(session.getOpenid());
            // TODO 可以增加自己的逻辑，关联业务相关数据
            JSONObject re = JSONObject.parseObject(JSONObject.toJSONString(session));
            //
            MemberListDTO member = memberListMapper.findByOpenId(session.getOpenid());
            if(Objects.isNull(member)){
                MemberListDTO newMember = new MemberListDTO();
                newMember.setOpenId(session.getOpenid());
                newMember.setUnionId(session.getUnionid());
                memberListMapper.insert(newMember);
                re.put("memberId", newMember.getMemberId());
            }else{
                re.put("memberId", member.getMemberId());
                re.put("memberName", member.getMemberName());
                re.put("memberPhone", member.getMemberPhone());
            }
            re.put("token", UUID.randomUUID().toString());
            return ReturnT.SUCCESS(re);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        } finally {
            //清理ThreadLocal
            WxMaConfigHolder.remove();
        }
    }

//    /**
//     * <pre>
//     * 获取用户信息接口
//     * </pre>
//     */
//    @ApiOperation(value = "获取小程序用户信息接口")
//    @PostMapping("/info")
//    public ReturnT info(@RequestBody @Validated WXInfoPO param) {
//        String appId = param.getAppId();
//        if (!wxMaService.switchover(appId)) {
//            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appId));
//        }
//
//        // 用户信息校验
//        if (!wxMaService.getUserService().checkUserInfo(param.getSessionKey(), param.getRawData(), param.getSignature())) {
//            WxMaConfigHolder.remove();//清理ThreadLocal
//            return ReturnT.ERROR("user check failed");
//        }
//
//        // 解密用户信息
//        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(param.getSessionKey(), param.getEncryptedData(), param.getIv());
//        WxMaConfigHolder.remove();//清理ThreadLocal
//        return ReturnT.SUCCESS(userInfo);
//    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @ApiOperation(value = "获取用户绑定手机号信息")
    @PostMapping("/phone")
    public ReturnT phone(@RequestBody @Validated WXInfoPO param) throws WxErrorException {
//        String appId = param.getAppId();
//        if (!wxMaService.switchover(appId)) {
//            return ReturnT.ERROR("未找到对应appId的配置，请核实！");
//        }
//
//        // 用户信息校验
//        if (!wxMaService.getUserService().checkUserInfo(param.getSessionKey(), param.getRawData(), param.getSignature())) {
//            WxMaConfigHolder.remove();//清理ThreadLocal
//            return ReturnT.ERROR("user check failed");
//        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(param.getCode());
        WxMaConfigHolder.remove();//清理ThreadLocal
        return ReturnT.SUCCESS(phoneNoInfo);
    }

}